<template>
  <div class="_container" style="height: auto; overflow: hidden; padding: 15px">
    <el-card>
      <el-card shadow="never" style="margin-bottom: 15px">
        <el-row style="line-height: 40px" aria-setsize="mini">
          <el-input style="width:260px" v-model="pageInfo.group_name" placeholder="分组"></el-input>
          <el-input style="width:260px" v-model="pageInfo.api_name" placeholder="接口名称"></el-input>
          <el-row style="float: right">
            <el-button type="primary" @click="query" icon="el-icon-search">搜索</el-button>
            <el-button type="primary" @click="openForm(null,'add')" icon="el-icon-plus">添加</el-button>
            <el-button type="primary" icon="el-icon-upload2" disabled>导入</el-button>
            <!--            <el-button type="primary" icon="el-icon-upload2" @click="exportExcelSelect">导出</el-button>-->
            <!--            <download-excel-->
            <!--                class = "export-excel-wrapper"-->
            <!--                :data = "data"-->
            <!--                name = "filename.xls">-->
            <!--              &lt;!&ndash; 上面可以自定义自己的样式，还可以引用其他组件button &ndash;&gt;-->
            <!--               <el-button type="primary" size="small">导出EXCEL</el-button>-->
            <!--            </download-excel>-->
<!--            <el-button onclick="window.open('http://www.jb51.net')">111</el-button>-->

            <el-button type="primary" icon="el-icon-download" @click="exportPostman">下载</el-button>
          </el-row>
        </el-row>
      </el-card>
      <el-table :data="data" ref="multipleTable" @selection-change="handleSelectionChange" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="group_name" label="分组" show-overflow-tooltip></el-table-column>
        <el-table-column prop="api_name" label="接口名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="hold_user" label="持有人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="fix_date" :formatter="dateFormat" show-overflow-tooltip label="更新时间"></el-table-column>
        <el-table-column prop="description" label="功能描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="请求方式">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.data.method === 'GET'">GET</el-tag>
            <el-tag type="warning" v-if="scope.row.data.method === 'POST'">POST</el-tag>
            <el-tag v-if="scope.row.data.method === 'PUT'">PUT</el-tag>
            <el-tag type="danger" v-if="scope.row.data.method === 'DELETE'">DELETE</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-link type="success" @click="openProcess(scope.row)">调试</el-link>
            <el-link type="primary" @click="openForm(scope.row,'update')">编辑</el-link>
            <el-link type="info" @click="openForm(scope.row,'copy')">复制</el-link>
            <el-link type="danger" @click="changeItem('该操作将会导致该接口从列表中移除！(不会影响该接口的正常功能)','HaveDeleted',scope.row._id)">
              通过
            </el-link>
            <el-link type="info" @click="openWatch(scope.row.api_name)">watch</el-link>
            <el-link type="primary" @click="openTaskForm(scope.row)">task</el-link>
            <el-link :disabled="!scope.row.task" :type="scope.row.task?'primary':'info'"
                     @click="openTask(scope.row.api_name)">任务
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <nav style="text-align: center">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="this.pageInfo.page"
            :page-size="this.pageInfo.page_size"
            layout="total, sizes, prev, pager, next"
            :total="total"
        ></el-pagination>
      </nav>
    </el-card>
    <el-dialog title="接口配置" :visible.sync="formDialogVisible" width="90%" :modal-append-to-body="false" center>
      <Designer :key=timer :form=row @listenToChildEvent="closeForm"></Designer>
    </el-dialog>
    <el-dialog title="调试" :visible.sync="processDialogVisible" width="50%" :modal-append-to-body="false" center>
      <Process :key=timer :form=row @listenToChildEvent="closeProcess"></Process>
    </el-dialog>
    <el-dialog title="watch" :visible.sync="watchDialogVisible" width="50%" :modal-append-to-body="false" center>
      <Watch :key=timer :watch_name=watch_name @listenToChildEvent="closeWatch"></Watch>
    </el-dialog>
    <el-dialog title="task" :visible.sync="taskFormDialogVisible" width="50%" :modal-append-to-body="false" center>
      <TaskForm :key="timer" :form=row @listenToChildEvent="closeTaskForm"></TaskForm>
    </el-dialog>
    <el-dialog title="任务" :visible.sync="taskDialogVisible" width="60%" :modal-append-to-body="false" center>
      <Task :key=timer :api_name=watch_name @listenToChildEvent="closeTask"></Task>
    </el-dialog>
  </div>
</template>

<script>
import {getNull, queryHandler, exportPostman} from "../../assets/js/designer";
import utils from "../../assets/js/utils";
import Designer from "./designer-form.vue"
import Process from "./designer-process.vue"
import Watch from "./designer-watch.vue"
import Task from "./designer-task-list.vue"
import TaskForm from "./designer-task-form.vue"

export default {
  components: {Designer, Process, Watch, Task, TaskForm},
  name: "designer-list",
  created() {
    this.query()
  },
  data() {
    return {
      pageInfo: {
        page: 1,
        page_size: 10,
        group_name: "",
        api_name: "",
      },  // 分页查询参数
      api_name: [],
      check_values: [],
      total: 0,
      data: [], // 列表值
      timer: '',
      argument: [],
      row: {},  // 行
      watch_name: "",
      task: [],
      taskDialogVisible: false,
      formDialogVisible: false,
      processDialogVisible: false,
      watchDialogVisible: false,
      taskFormDialogVisible: false,

      //导出表格字段及formatter信息
      exportExcelArry: [],
      //导出excel表格id及excel名称
      exportExcelInfo: {
        excelId: 'record-table',
        excelName: '属性表.xlsx'
      },
      //需要导出的table数据
      tableAllData: [],
    }
  },
  methods: {
    dateFormat: function (row, column) {
      return utils.dateFormat(row, column)
    },
    query: function () {
      let that = this
      let page = that.pageInfo.page
      let page_size = that.pageInfo.page_size
      let filter = {}
      if (!utils.isEmpty(that.pageInfo.api_name)) {
        filter['api_name'] = {'$regex': that.pageInfo.api_name}
      }
      if (!utils.isEmpty(that.pageInfo.group_name)) {
        filter['group_name'] = {'$regex': that.pageInfo.group_name}
      }

      queryHandler(filter, page, page_size).then((response) => {
        if (response.data.code === 0) {
          this.data = response.data.result.data
          this.total = response.data.result.total
        }
      })
    },
    // removeItem: function (id) {
    //   utils.updateStatus("design", "HaveDeleted", id)
    //   this.query()
    // },
    changeItem: function (message, action, id) {
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        utils.updateStatus("design", action, id)
        this.query()
      }).catch(() => {
        this.$message({
          message: "已取消",
          type: "info"
        })
      })
    },
    handleSizeChange: function (page_size) {
      console.log(page_size)
      this.pageInfo.page_size = page_size;
      this.query()
    },
    handleCurrentChange: function (page) {
      this.pageInfo.page = page;
      this.query()
    },
    openForm: function (row, type) {
      this.timer = new Date().getTime()
      switch (type) {
        case 'add':
          this.row = getNull()
          break
        case 'update':
          this.row = row
          break
        case 'copy':
          row['_id'] = ""
          this.row = row
          break
        default:
          break
      }
      this.formDialogVisible = true;
    },
    closeForm: function (formDialogVisible) {
      this.formDialogVisible = formDialogVisible
      this.query()
    },
    openProcess: function (row) {
      this.timer = new Date().getTime()
      this.row = row
      this.processDialogVisible = true;
    },
    closeProcess: function (processDialogVisible) {
      this.processDialogVisible = processDialogVisible
      this.query()
    },
    openWatch: function (api_name) {
      this.timer = new Date().getTime()
      this.watch_name = api_name;
      this.watchDialogVisible = true;
    },
    closeWatch: function (watchDialogVisible) {
      this.watchDialogVisible = watchDialogVisible
      this.query()
    },
    openTask: function (api_name) {
      this.timer = new Date().getTime()
      this.watch_name = api_name
      this.taskDialogVisible = true;
    },
    closeTask: function (taskDialogVisible) {
      this.taskDialogVisible = taskDialogVisible
      this.query()
    },
    openTaskForm: function (row) {
      this.timer = new Date().getTime()
      this.row = row
      this.taskFormDialogVisible = true;
    },
    closeTaskForm: function (taskFormDialogVisible) {
      this.taskFormDialogVisible = taskFormDialogVisible
      this.query()
    },
    exportPostman: function () {
      console.log(this.api_name)
      if (this.api_name.length !== 0) {
        const name = 'p' + this.pageInfo.page + this.pageInfo.group_name + '-' + this.pageInfo.api_name
        exportPostman(name, this.api_name)
      } else {
        this.$message({
          message: "请选择需要下载的接口",
          type: "warning"
        })
      }
    },
    handleSelectionChange(val) {
      let apiName = []
      for (let i = 0; i < val.length; i++) {
        apiName.push(val[i].api_name)
      }
      this.check_values = val
      this.api_name = apiName
    },
    exportExcelSelect() {
      if (this.check_values.length === 0) {
        global.message('请勾选操作项')
        return;
      }
      //根据表头声明 tableArry
      this.exportExcelArry = [{
        prop: 'group_name',
        label: '用户手机号',
        formatterFlag: false
      }, {
        prop: 'userFundRedEnvelopRecord.status',
        label: '状态',
        formatterFlag: true,
        formatterType: 'common-type',
        formatterInfo: [{value: 0, label: '未完成'}, {value: 1, label: '已完成'}]
      }, {
        prop: 'userFundRedEnvelopRecord.name',
        label: '任务名称',
        formatterFlag: false
      }]
      //将选中项传给this. tableAllData
      this.tableAllData = this.check_values
      // console.log(this.tableAllData)
      //需要延时调导出方法，为了等待数据初始化到列表中
      setTimeout(() => {
        this.$refs.myChild.exportExcel();
      }, 500)
    },
    exportExcel() {
      this.initData('export-excel')
      //获取到表格数据的值并赋给this.tableAllData
      //同样延时调导出方法，需在initData('export-excel')方法执行成功后调this.$refs.myChild.exportExcel();方法
      this.$refs.myChild.exportExcel()
    }
  }
}
</script>

<style scoped>

</style>
